import 'dart:core';

import 'package:shared_preferences/shared_preferences.dart';

enum WeightUnit { jin, kg }

enum SpKey {
  token,
  refreshToken,
  weightUnit,
  hookWeight,
  tokenExpiresTime,
}

class Global {
  static SharedPreferences? _sp;

  static double? getDouble(SpKey spKey, {double? defaultValue}) {
    return _sp?.getDouble(spKey.name) ?? defaultValue;
  }

  static setDouble(SpKey spKey, double value) {
    _sp?.setDouble(spKey.name, value);
  }

  static int? getInt(SpKey spKey, {int? defaultValue}) {
    return _sp?.getInt(spKey.name) ?? defaultValue;
  }

  static setInt(SpKey spKey, int value) {
    _sp?.setInt(spKey.name, value);
  }

  static String? getString(SpKey spKey, {String? defaultValue}) {
    return _sp?.getString(spKey.name) ?? defaultValue;
  }

  static setString(SpKey spKey, String value) {
    _sp?.setString(spKey.name, value);
  }

  static remove(SpKey spKey) {
    _sp?.remove(spKey.name);
  }

  static WeightUnit get weightUnit => WeightUnit.values
      .byName(_sp?.getString(SpKey.weightUnit.name) ?? WeightUnit.jin.name);

  static set weightUnit(WeightUnit weightUnit) =>
      _sp?.setString(SpKey.weightUnit.name, weightUnit.name);

  static String get token => _sp?.getString(SpKey.token.name) ?? "";

  static set token(String token) => _sp?.setString(SpKey.token.name, token);

  static bool get isLogin => token.isNotEmpty;

  static Future<void> init() async =>
      _sp = await SharedPreferences.getInstance();

  static Future<void> clear() async => await _sp?.clear();
}
